package com.mlog.njyjy.ndop.msg.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.google.gson.*;
import com.mlog.njyjy.ndop.msg.admin.service.AlarmManagerService;
import com.mlog.njyjy.ndop.msg.common.domain.DelayMonitor;
import com.mlog.njyjy.ndop.msg.common.domain.Flow;
import com.mlog.njyjy.ndop.msg.common.domain.NodeItem;
import com.mlog.njyjy.ndop.msg.persistence.dao.DelayMonitorRepository;
import com.mlog.njyjy.ndop.msg.persistence.dao.FlowRepository;
import com.mlog.njyjy.ndop.share.sql.support.SqlSort;
import com.mlog.njyjy.ndop.share.sql.support.SqlTableUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author zyz
 * @version v1.0, 2020/8/17
 */
@Slf4j
@Service
public class AlarmManagerServiceImpl implements AlarmManagerService {

    @Autowired
    private DelayMonitorRepository repository;

    @Autowired
    private FlowRepository flowRepository;

    @Override
    public List<DelayMonitor> list() {
        return repository.findAll(new SqlSort().setField("create_at").setOrder(SqlSort.Order.DESC));
    }

    @Override
    public List<DelayMonitor> listByType(String typeName) {
        List<Flow> flowList = flowRepository.findByField("type_name", typeName);
        return listByFlow(flowList);
    }

    @Override
    public List<DelayMonitor> listByTypeAndTimes(String typeName, String times) {
        List<Flow> flowList = flowRepository.find("select * from " + SqlTableUtil.getTblName(Flow.class)
                + " where type_name = ? and times = ? ", typeName, times);
        return listByFlow(flowList);
    }

    @Override
    public List<DelayMonitor> listByFlow(List<Flow> flowList) {
        List<DelayMonitor> delayMonitors = new ArrayList<>();

        if (flowList != null) {
            flowList.forEach(flow -> {
                List<NodeItem> nodeItemList = flow.getItems();
                if (nodeItemList != null) {
                    List<Long> itemIds = nodeItemList.stream().map(NodeItem::getId).collect(Collectors.toList());
                    List<DelayMonitor> monitorList = repository.find("select * from " + SqlTableUtil.getTblName(DelayMonitor.class)
                            + " where node_item_id in (" + itemIds.stream().map(String::valueOf).collect(Collectors.joining(",")) + ")");
                    delayMonitors.addAll(monitorList);
                }
            });
        }
        return delayMonitors;
    }

    @Override
    public boolean save(DelayMonitor delayMonitor) {
        Long id = delayMonitor.getId();
        if (id == null) {
            //新增
            return repository.insert(delayMonitor);
        } else {
            //更新
            return repository.update(delayMonitor);
        }
    }

    @Override
    public List<DelayMonitor> importFile(byte[] sourceBytes) {
        String string = new String(sourceBytes);
        return sync(string);
    }

    @Override
    public List<DelayMonitor> syncDelayMonitor() {
        String string = ""; //fromApi
        return sync(string);
    }

    @Override
    public List<DelayMonitor> sync(String string) {
        JsonElement jsonElement = new JsonParser().parse(string);
        boolean isArr = jsonElement.isJsonArray();
        if (isArr) {
            List<DelayMonitor> monitorList = new ArrayList<>();
            JsonArray jsonArray = jsonElement.getAsJsonArray();
            for (JsonElement element : jsonArray) {
                DelayMonitor delayMonitor = new Gson().fromJson(element, DelayMonitor.class);
                monitorList.add(delayMonitor);
            }
            repository.insert(monitorList);
        } else {
            DelayMonitor delayMonitor = new Gson().fromJson(string, DelayMonitor.class);
            repository.insert(delayMonitor);
        }
        return list();
    }


    @Override
    public boolean downloadTpl(List<DelayMonitor> list) {
        return false;
    }

    @Override
    public boolean changeStatus(int status, String ids) {
        boolean flag = true;
        if (StrUtil.isNotBlank(ids)) {
            String[] idArr = ids.split(",");

            for (String id : idArr) {
                DelayMonitor monitor = repository.findFirst("select * from " + SqlTableUtil.getTblName(DelayMonitor.class)
                        + " where id = " + Long.valueOf(id));
                if (monitor != null) {
                    monitor.setStatus(status);
                    boolean success = repository.update(monitor);
                    if (!success) {
                        log.error("update delayMonitor failed, id= {}", id);
                        flag = false;
                    }
                } else {
                    log.error("can't find the delayMonitor, id = {}", id);
                    flag = false;
                }

            }
        }
        return flag;
    }
}
